import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;


import org.apache.http.HttpResponse;
import org.json.simple.JSONArray;

import com.dropbox.client.DropboxClient;
import com.dropbox.client.DropboxException;

public class DropboxCommunicator implements Serializable{

	//static DropboxClient dbClient;  //removed by u099048h
	static String root;
	static String path;
	static String backUpPath;
	
	static Map initialMeta;
	
	File logFile;
	
	//added by u099048h
	String userName;
	Stylepad editor;
	static SecurityHandler securityHandler;
	private static SubFileHandler subFile;
	
	public static final int autoUnlockTime = 3; // in minutes
	
	//public static SmartManager sm;
	
	public DropboxCommunicator(DropboxClient client, String rootname, String pathname, String backUpPathName, Stylepad sEditor, String username){
		//dbClient = client;
		root = rootname;
		path = pathname;
		backUpPath = backUpPathName; 
		
		//added by u099048h
		userName = username;
		editor = sEditor;
		securityHandler = new SecurityHandler(client, rootname, pathname, backUpPathName, editor, userName);
		subFile = new SubFileHandler();
	}
	
	// Author@U097023U 
	public static void createNewFolder (String folderName)
	{
		//changed u099048h
		//dbClient.fileCreateFolder (root, folderName, null);
		securityHandler.fileCreateFolder (folderName, null);
		
		System.out.println ("Create a backup folder: " + folderName);
	}
	
	public static void deleteFolder (String folder)
	{
		//changed u099048h
		//dbClient.fileDelete (root, folder, null);
		securityHandler.fileDelete (folder, null, null);
	}
	
	// Author@U097023U 
	public static void copyFile (String toFolder, String fileToName, String fileFromName)
	{
		//changed u099048h
		//dbClient.fileCopy (root, path + "/" + fileFromName, toFolder + "/" + fileToName, null);
		securityHandler.fileCopy (toFolder, fileToName, fileFromName);
		System.out.println ("Copy the file to its backup folder: " + toFolder + "/" + fileToName);
	}
	
	// Author@U097023U 
	public static void moveFile (String fromFolder, String fileFromName, String fileToName)
	{
		//changed u099048h
		//dbClient.fileMove (root, fromFolder + "/" + fileFromName, path + "/" + fileToName, null);
		securityHandler.fileMove (fromFolder, fileFromName, fileToName);
		System.out.println ("Move the back up file back to its original folder: " + fromFolder + "/" + fileFromName);
	}
	
	
	
	// Author@U097023U 
	public static String getModifiedTime (String filename)
	{
		Map metadata = null;
		
		//changed u099048h
		//metadata = dbClient.metadata (root, path + "/" + filename, 100, null, false, false, null);
		metadata = securityHandler.metadata(filename, false, 100, null, false, false, null);
		
		if (metadata != null && metadata.get ("modified") != null)
		{
			return (String) metadata.get("modified");
		}
		
		return "";
	}
	
	// Author@U097023U
	public static void renameRemoteFile (String oldName, String newName)
	{
		Map resp = null;
		
		//changed u099048h
		//resp = dbClient.fileMove (root, path + "/" + oldName, path + "/" + newName, null);
		resp = securityHandler.fileMove (null,oldName, newName);
		
		Statistics.moveRequest++;
		System.out.println("DC##33 Add 1 to move request: " + Statistics.moveRequest);
		Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
		
		if(resp == null){
			System.out.println("rename file failed: "+oldName);
		}
		if(resp.get("ERROR") != null){
			System.out.println("rename file failed: "+oldName + ", error: " + resp.get("ERROR"));
		}
	}
	
	// Author@U097023U
	public static String unlockExpiredLockedFile (String fileName)
	{
		String unlockedName = fileName;
		if (SDAction.isFileLocked (fileName))
		{
			String modifiedTime = getModifiedTime (fileName);
			
			if (compareTime (modifiedTime) >= autoUnlockTime)
			{
				// The lock has expired, unlock it.
				unlockedName = SDAction.renameFromLockToUnlock (fileName);
				DropboxCommunicator.renameRemoteFile (fileName, unlockedName);
			}
		}
		
		return unlockedName;
	}
	
	

	@SuppressWarnings("unchecked")
	public static boolean lockFile(String filename){
		
		if(filename == null){
			System.out.println("Invalid file name");
			return false;
		}
		if(filename.endsWith("N")){
			//String newfilename = filename.substring(0, filename.length()-1)+"L";
			String newfilename = SDAction.renameFromUnlockToLock(filename);
			Map resp = null;
			
			//changed u099048h
			//resp = dbClient.fileMove(root, path+"/"+filename, path+"/"+newfilename, null);
			resp = securityHandler.fileMove(null, filename, newfilename);

			Statistics.moveRequest ++;
			System.out.println("DC##33 Add 1 to move request: " + Statistics.moveRequest);
			Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
			if(resp == null){
				System.out.println("rename file failed: "+filename);
				return false;
			}
			if(resp.get("ERROR") != null){
				System.out.println("rename file failed: "+filename + ", error: " + resp.get("ERROR"));
				return false;
			}
			addtoIgnoreFilelist(filename);
			return true;
		}
		else if(filename.endsWith("L"))
		{
			/**
			 * get the modified time of that file,
			 * if it is modified within one hour, then user cannot lock it again,
			 * else, try to unlock it first and then lock
			 */
			Map metadata = null;
			
			//changed u099048h
			//metadata = dbClient.metadata(root, path+"/"+filename, 100, null, false, false, null);
			metadata = securityHandler.metadata(filename, false, 100, null, false, false, null);

			Statistics.metadataRequest ++;
			System.out.println("DC##^^ Add 1 to metadata request: " + Statistics.metadataRequest);
			Statistics.writeToLog("Metadata, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
			
			if(metadata != null && metadata.get("modified") != null){
				String modified = (String) metadata.get("modified");
				if(compareTime(modified) < autoUnlockTime){
					System.out.println("the file has been locked within " + autoUnlockTime + " minutes(s), cannot lock again!");
					return false;
				}
				else
				{
					//String tmpname = filename.substring(0, filename.length()-1)+"N";
					String tmpname = SDAction.renameFromLockToUnlock(filename);
					Map resp = null;
					
					//changed u099048h
					//resp = dbClient.fileMove(root, path+"/"+filename, path+"/"+tmpname, null);
					resp = securityHandler.fileMove(null, filename, tmpname);
					
					Statistics.moveRequest ++;
					System.out.println("DC##11 Add 1 to move request: " + Statistics.moveRequest);
					Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
					
					if(resp != null && resp.get("ERROR") == null){
						addtoIgnoreFilelist(filename);
						
						filename = SDAction.renameFromUnlockToLock(tmpname);
						
						//changed u099048h
						//resp = dbClient.fileMove(root, path+"/"+tmpname, path+"/"+filename, null);
						resp = securityHandler.fileMove(null, tmpname, filename);
						
						Statistics.moveRequest ++;
						System.out.println("DC##22 Add 1 to move request: " + Statistics.moveRequest);
						Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
						
						if(resp != null && resp.get("ERROR") == null){
							addtoIgnoreFilelist(filename);
							return true;
						}
							
						
						return false;
					}
					return false;
				}
			}
			return false;
		}
		else{
			System.out.println("invalid file name: "+filename);
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static boolean unlockFile(String filename){
		
		if(filename == null){
			System.out.println("Invalid file name");
			return false;
		}
		if(!filename.endsWith("L")){
			System.out.println("file name not end with L: "+filename);
			return false;
		}
		//String newname = filename.substring(0, filename.length()-1)+"N";
		String newname = SDAction.renameFromLockToUnlock(filename);
		Map resp = null;
		
		//changed u099048h
		//resp = dbClient.fileMove(root, path+"/"+filename, path+"/"+newname, null);
		resp = securityHandler.fileMove(null, filename, newname);
		
		Statistics.moveRequest ++;
		System.out.println("DC##11 Add 1 to move request: " + Statistics.moveRequest);
		Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
		
		if(resp == null){
			System.out.println("rename file failed: "+filename);
			return false;
		}
		if(resp.get("ERROR") != null){
			System.out.println("rename file failed: "+filename + ", error: " + resp.get("ERROR"));
			return false;
		}
		addtoIgnoreFilelist(filename);
		return true;
	}
	
	/**
	 * responds to the "Next" button, get the next file
	 * 
	 * @param currentFilename
	 * @return
	 * @throws DropboxException
	 */
	@SuppressWarnings("unchecked")
	public static Map loadNextFile(String currentFilename){
		
		for(int i = 0; i < 3; i++){		// check for at most three times
			Map meta = null;
			ArrayList<String> filenameList = new ArrayList<String>();
			//changed u099048h
			//meta = dbClient.metadata(root, path, 100, null, true, false, null);
			do{
				meta = securityHandler.metadata(null, false, 100, null, true, false, null);
			
				Statistics.metadataRequest ++;
				System.out.println("DC## MetadataRequest Add 1: "+ Statistics.metadataRequest);
				Statistics.writeToLog("Metadata, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
				
				filenameList = getFilenameListFromMeta(meta);
			}while(filenameList == null); //request for metadata again if the filenamelist is null
			
			ArrayList<String> mainFilenameList = getMainFilenameList(filenameList);
			String[] temp = currentFilename.split("_");
			String currentMainname = temp[0] + "_" + temp[1];
			int index = findIndex(currentMainname, mainFilenameList);
			if(index == mainFilenameList.size()-1){
				System.out.println("Already the last file, no more next files!");
				return null;
			}
			
			String nextFilename = filenameList.get(index+1);
			nextFilename = unlockExpiredLockedFile (nextFilename);
			
			System.out.println("next file name: " + nextFilename);
			
			Document loadedInDoc = loadSingleFile (nextFilename);
			if(loadedInDoc != null){
				Map map = new HashMap();
				map.put("filename", nextFilename);
				map.put("doc", loadedInDoc);
				return map;
			}
		}
		return null;
	}
	
	/**
	 * responds to the "Previous" button, get the previous file
	 * 
	 * @param currentFilename
	 * @return
	 * @throws DropboxException
	 */
	@SuppressWarnings("unchecked")
	public static Map loadPreviousFile(String currentFilename){
		
		for(int i = 0; i < 3; i++){		// check for at most three times
			Map meta = null;
			ArrayList<String> filenameList = new ArrayList<String>();
			//changed u099048h
			//meta = dbClient.metadata(root, path, 100, null, true, false, null);
			do{
				meta = securityHandler.metadata(null, false, 100, null, true, false, null);
				
				Statistics.metadataRequest ++;
				System.out.println("DC##11 Add 1 to metadata request: "+Statistics.metadataRequest);
				Statistics.writeToLog("Metadata, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
				
				filenameList = getFilenameListFromMeta(meta);
			} while (filenameList == null); //request again if the filenameList is null
			
			
			ArrayList<String> mainFilenameList = getMainFilenameList(filenameList);
			String[] temp = currentFilename.split("_");
			String currentMainname = temp[0] + "_" + temp[1];
			int index = findIndex(currentMainname, mainFilenameList);
			if(index == 0){
				System.out.println("Already the first file, no more previous files!");
				return null;
			}
			String toLoadFile = filenameList.get(index-1);
			toLoadFile = unlockExpiredLockedFile (toLoadFile);
			
			Document doc = loadSingleFile(toLoadFile);
			if(doc != null){
				Map map = new HashMap();
				map.put("filename", toLoadFile);
				map.put("doc", doc);
				return map;
			}
		}
		return null;
	}
	
	private static int findIndex(String currentMainname, ArrayList<String> mainFilenameList) {

		for(int i = 0; i < mainFilenameList.size(); i++){
			if(mainFilenameList.get(i).equals(currentMainname))
				return i;
		}
		return -1;
	}

	@SuppressWarnings("unchecked")
	public static ArrayList<String> getFilenameListFromMeta(Map meta){
		
		Object json_contents = meta.get("contents");
		System.out.println("GET FILENAME LIST FROM META");
		if (!(json_contents != null && json_contents instanceof JSONArray)){
			System.out.println("no contents from meta");
		}
        if (json_contents != null && json_contents instanceof JSONArray) {
        	System.out.println("SIZE OF JSONARRAY: " + ((JSONArray)json_contents).size());
        	//if no contents, just return
        	if (((JSONArray)json_contents).size() == 0)
        		return null;
        		
            Object entry;
            Iterator it = ((JSONArray)json_contents).iterator();
            
            ArrayList<String> filenameList = new ArrayList<String>();
            
            while (it.hasNext()) {
                entry = it.next();
                if (entry instanceof Map) {
                	String path1 = (String)((Map) entry).get("path");
                	String[] dirs = path1.split("/"); // last element of dirs should be the file name
                	
                	if(!path1.equals(path + "/" + "server_log_file_N")){
                		if(!path1.equals(path + "/" + "server_log_file_L")){
	                		if (dirs != null){
		                		filenameList.add(dirs[dirs.length - 1]); 
		                		System.out.println("Add: " + dirs[dirs.length - 1]);
	                		}
                		}
                	}
                }
            }
            
            ArrayList<String> sortedList = sortFilenameListBySDNo(filenameList);
            
            //added u099048h
            securityHandler.filesValidationChecks(sortedList);
            
            return sortedList;
        }
        return null;
	}
	
	public static ArrayList<String> sortFilenameListBySDNo(ArrayList<String> filenameList){
		
		if(filenameList == null)
			return null;
		
		for(int i = 0; i < filenameList.size() - 1; i++)
			for(int j = i+1; j < filenameList.size(); j++){
				String iName = filenameList.get(i);
				String jName = filenameList.get(j);
				if(SDAction.getSDNoFromFileName(iName) > SDAction.getSDNoFromFileName(jName)){
					filenameList.set(i, jName);
					filenameList.set(j, iName);
				}
			}
		
		return filenameList;
	}
	
	public static ArrayList<String> getMainFilenameList(ArrayList<String> fullFilenameList){
		
		if(fullFilenameList == null)
			return null;
		
		ArrayList<String> mainFilenameList = new ArrayList<String>();
		
		for(int i = 0; i < fullFilenameList.size(); i++){
			String[] name = fullFilenameList.get(i).split("_");
			mainFilenameList.add(name[0]+"_"+name[1]);
		}
		return mainFilenameList;
	}

	@SuppressWarnings("deprecation")
	public static int compareTime (String time){
		
		String date[] = time.split(" ");
		String hour[] = date[4].split(":");
		int month=-1;
		try {
			month = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(date[2]).getMonth();
			System.out.println(month);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		GregorianCalendar calen = new GregorianCalendar(Integer.parseInt(date[3]), month, 
				Integer.parseInt(date[1]), Integer.parseInt(hour[0]), Integer.parseInt(hour[1]), Integer.parseInt(hour[2]));
		Date d1 = calen.getTime();
		//System.out.println(d1);
		
		long t1 = d1.getTime() + TimeZone.getDefault().getRawOffset();
		
		Date d2 = new Date();
		long t2 = d2.getTime();
		
		return (int)(t2-t1)/1000/60;
	}

	public static Document loadSingleFile (final String filename)
	{	
		HttpResponse resp = null;
		
		//changed u099048h
		//resp = dbClient.getFile (root, path + "/" + filename);
		boolean statusCodeCheck = true;
		
		do{
			resp = securityHandler.getFile(filename);
			
			if(resp == null){
				System.out.println("Cannot load file: " + filename + ". Retrying.");
				statusCodeCheck = false;
			}else{
				statusCodeCheck = true;
			}
			int status = resp.getStatusLine ().getStatusCode ();
			if(status != 200){
				System.out.println("Invalid status code for file: " + filename + ". Retrying.");
				statusCodeCheck = false;
			}else{
				statusCodeCheck = true;
			}
		}while(statusCodeCheck == false);		
		
		Statistics.downloadRequest ++;
		System.out.println("DC##123 Add 1 to download request: "+Statistics.downloadRequest);
		Statistics.writeToLog("Download, "+Statistics.getCurrentTime()+", "+resp.getEntity().getContentLength()+" byte", "log.txt");
		
		Document doc = null;
		
		//ADDED u099048h
		try {	
			InputStream in = resp.getEntity().getContent();		
			OutputStream out = new FileOutputStream("sub_file" + filename);
			
			int numRead = 0;
			byte[] buf = new byte[1024];
			
			while ((numRead = in.read(buf)) >= 0){
				out.write(buf, 0, numRead);
			}
			
			out.close();
			in.close();

			InputStream in2 = new FileInputStream("sub_file" + filename);	
			System.out.println(filename);
			
			String unlockedName;
			if(SDAction.isFileLocked (filename))
				unlockedName = SDAction.renameFromLockToUnlock (filename);
			else
				unlockedName = filename;
			
			if (!subFile.subFileHMACCheck(in2, unlockedName)){
				//print some error
		
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		try {
			InputStream in3 = new FileInputStream("sub_file" + filename);	
			if (!subFile.decryptSubFile(in3, "d_sub_file" + filename)){
				//print some error
		
			}
			try {
				in3.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
			
		File en_file = new File("sub_file" + filename);
		File d_file = new File("d_sub_file" + filename);
		
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d_sub_file" + filename));
			try {
				doc = (Document)ois.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			ois.close();
			en_file.delete();
			d_file.delete();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			doc.remove(doc.getLength()-1, 1);
			/*if(SDAction.isFileLocked(filename)){
				//((DefaultStyledDocument)doc).setCharacterAttributes(0, doc.getLength(), SmartManager.otherLockAttr, false);
				sm.drawLockByOtherHighlight ();
			}*/
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}
/*	
	public static void saveSingleFile(File file){
		
		new FileSaver(dbClient, root, path, file).start();
		
		addtoIgnoreFilelist(file.getName());
	}
	*/
	
	//************THIS FUNCTION NEEDS A MODIFICATION FILE LOGFILE UPDATE***************
	/*ADDED attribute ops:
	Modification of sub-file -> 0
	Add new sub-file -> 1
	Delete sub-file -> 2
	*/

	public static void saveSingleFile(String filename, Document doc, int ops ){
/*		
		MutableAttributeSet attr = new SimpleAttributeSet();
    	StyleConstants.setBackground(attr, Color.white);
    	((DefaultStyledDocument) doc).setCharacterAttributes(0, doc.getLength(), attr, false);
    	*/
		long lStartTime = System.currentTimeMillis();
		
		File file = new File("d_"+filename);
		
		try {
			FileOutputStream fstrm = new FileOutputStream(file, false);
			ObjectOutput ostrm = new ObjectOutputStream(fstrm);
			ostrm.writeObject(doc);
			ostrm.flush();
			fstrm.close();
			ostrm.close();
		} catch (Exception e) {
			file.delete();
		}
		
		//get the unlocked filename to hash
		String unlockedName = SDAction.renameFromLockToUnlock (filename);
		
		byte[] HMAC = subFile.saveSubFile(filename, unlockedName);
		if(HMAC.equals(null)){
			System.out.println("HMAC for subfile failed");
				return;
		}
		
		//changed u099048h
		//HttpResponse resp = dbClient.putFile(root, path, file);
		//System.out.println("HMAC SIZE = " + HMAC.length);
		HttpResponse resp = securityHandler.putFile(new File(filename),ops, HMAC);
		
		if(resp == null){
			System.out.println("upload file failed: " + file.getName());
			file.delete();
			return;
		}
		int code = resp.getStatusLine().getStatusCode();
		if(code != 200){
			System.out.println("upload file failed: " + file.getName()+", invalid code: "+code);
			file.delete();
			return;
		}
		
		Statistics.uploadRequest ++;
		System.out.println("DC##* Add 1 to upload request: "+Statistics.uploadRequest);
		Statistics.writeToLog("Upload, "+Statistics.getCurrentTime()+", "+file.length()+" byte", "log.txt");
		
		if(file.exists())
			file.delete();			
		
		addtoIgnoreFilelist(file.getName());
		
		/*long lEndTime = System.currentTimeMillis();
		long difference = lEndTime - lStartTime;
		
		try {
		    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("EfficiencyCheck", true)));
		    //out.println("Save File. Time Elapsed in milliseconds: " + difference);
		    out.close();
		} catch (IOException e) {
		    //
		}*/
	}
	
	@SuppressWarnings("unchecked")
	public static boolean renameFile(String oldName, String newName){
		
		Map resp = null;
		//changed u099048h
		//resp = dbClient.fileMove(root, path+"/"+oldName, path+"/"+newName, null);
		resp = securityHandler.fileMove(null, oldName, newName);
		
		Statistics.moveRequest ++;
		System.out.println("DC##1245 Add 1 to move file request: "+Statistics.moveRequest);
		Statistics.writeToLog("Rename, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
		
		if(resp == null){
			System.out.println("Cannot rename from " + oldName +" to " + newName);
			return false;
		}
		
		if(resp.get("ERROR") != null){
			System.out.println("Cannot rename from " + oldName +" to " + newName + ", error " + resp.get("ERROR"));
			return false;
		}
		addtoIgnoreFilelist(oldName);
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public static boolean deleteSingleFile(String filename){
		
		
		Map resp = null;
		
		//changed u099048h
		//resp = dbClient.fileDelete(root, path+"/"+filename, null);
		resp = securityHandler.fileDelete(null, path+"/"+filename, null);
		
		Statistics.deleteRequest ++;
		System.out.println("DC##ACG Add 1 to delete file request.");
		Statistics.writeToLog("Delete, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
		
		if(resp == null){
			System.out.println("Cannot delete file " + filename);
			return false;
		}
		
		if(resp.get("ERROR") != null){
			System.out.println("Cannot delete file " + filename + ", error " + resp.get("ERROR"));
			return false;
		}
		addtoIgnoreFilelist(filename);
		
		return true;
	}
	@SuppressWarnings("unchecked")
	public static ArrayList<String> getDirInfo(){
		
		Map meta = null;
		ArrayList<String> filelist = new ArrayList<String>();
		
		//changed u099048h
		//meta = dbClient.metadata(root, path, 100, null, true, false, null);
		do{
			meta = securityHandler.metadata(null, false, 100, null, true, false, null);
		
			Statistics.metadataRequest ++;
			System.out.println("DC##$$ Add 1 to metadata request: " + Statistics.metadataRequest);
			Statistics.writeToLog("Metadata, "+Statistics.getCurrentTime()+", 0 byte", "log.txt");
			
			filelist = getFilenameListFromMeta(meta);
		}while (filelist == null);//if filelist is null then request for the metadata again
		
		return filelist;
	}

	public void startUpdateChecker(SmartManager sm){
		//changed u099048h
		//new UpdateChecker(dbClient, root, path, 10000, initialMeta, sm, backUpPath).start();
		new UpdateChecker(securityHandler, root, path, 10000, initialMeta, sm, backUpPath).start();
	}
	
	public static UpdateChecker createUpdateChecker (SmartManager sm)
	{
		//changed u099048h
		//return new UpdateChecker(dbClient, root, path, 10000, initialMeta, sm, backUpPath);
		return new UpdateChecker(securityHandler, root, path, 10000, initialMeta, sm, backUpPath);
	}
	
	public static void addtoIgnoreFilelist(String fullname){
		
		String[] name = fullname.split("_");
		String mainname = name[0]+"_"+name[1];
		if(!SmartManager.ignoredFilelist.contains(mainname))
			SmartManager.ignoredFilelist.add(mainname);
	}

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
}
